package com.exin.openfeign;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

public class FeignRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
	
	private Map<String , RequestMappingInfo> maps = new HashMap<String , RequestMappingInfo>();
	
	
	@Override
	protected void registerHandlerMethod(Object handler, Method method, RequestMappingInfo mapping) {
		super.registerHandlerMethod(handler, method, mapping);
	}
	
	
	@Override
	public void registerMapping(RequestMappingInfo mapping, Object handler, Method method) {
		super.registerMapping(mapping, handler, method);
	}
	
	
	protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
		RequestMappingInfo mappingInfo =  super.getMappingForMethod(method, handlerType);
		if(mappingInfo!=null) {
			PatternsRequestCondition pc = mappingInfo.getPatternsCondition();
			if(pc!=null) {
				Set<String> httpMethods = mappingInfo.getPatternsCondition().getPatterns() ;
				for (String httpMethod : httpMethods) {
					maps.put(httpMethod, mappingInfo);
				}
			}
		}
		return mappingInfo;
	}
	
	
	public RequestMappingInfo get(Method method) {
		String[] paths = null;
		if(method.isAnnotationPresent(GetMapping.class)) {
			paths = method.getAnnotation(GetMapping.class).value();
		}else if(method.isAnnotationPresent(PostMapping.class)) {
			paths = method.getAnnotation(PostMapping.class).value();
		}else {
			paths = method.getAnnotation(RequestMapping.class).value();
		}
		
		if(paths == null || paths.length == 0) {
			throw new RuntimeException(method+":Mapping 未配置");
		}
		
		String key = paths[0];
		return maps.get(key);
	}
	
}
